package com.axin.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.axin.common.core.constant.CacheConstants;
import com.axin.common.core.exception.ServiceException;
import com.axin.common.core.domain.web.TableDataInfo;
import com.axin.common.mybatis.utils.PageUtils;
import com.axin.common.redis.utils.RedisUtils;
import com.axin.system.api.domain.SysDictData;
import com.axin.system.api.domain.SysDictType;
import com.axin.system.mapper.SysDictTypeMapper;
import com.axin.system.service.ISysDictDataService;
import com.axin.system.service.ISysDictTypeService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

/**
 * 字典类型 业务层处理
 *
 * @Author axin
 * @Date 2021/10/27 10:51
 **/
@Service
public class SysDictTypeServiceImpl extends ServiceImpl<SysDictTypeMapper, SysDictType> implements ISysDictTypeService {


    @Autowired
    private ISysDictDataService dictDataService;

    @Autowired
    private RedisUtils redisUtils;

    /**
     * 项目启动时，初始化字典到缓存
     */
    @PostConstruct
    public void init() {
        loadingDictCache();
    }

    public void loadingDictCache() {
        List<SysDictType> dictTypeList = list();
        for (SysDictType dictType : dictTypeList) {
            List<SysDictData> dictDataList = dictDataService.selectDictDataByType(dictType.getDictType());
            redisUtils.set(getCacheKey(dictType.getDictType()), JSONObject.toJSONString(dictDataList));
        }
    }

    public void clearDictCache() {
        Collection<String> keys = redisUtils.keys(CacheConstants.SYS_DICT_KEY + "*");
        redisUtils.delete(keys);
    }

    /**
     * 设置cache key
     *
     * @param configKey 参数键
     * @return 缓存键key
     */
    public static String getCacheKey(String configKey) {
        return CacheConstants.SYS_DICT_KEY + configKey;
    }

    /**
     * 根据字典类型ID查询信息
     *
     * @param dictId 字典类型ID
     * @return 字典类型
     */
    @Override
    public SysDictType selectDictTypeById(Long dictId) {
        return getById(dictId);
    }

    /**
     * 根据条件分页查询字典类型
     *
     * @param dictType
     * @return
     */
    @Override
    public TableDataInfo<SysDictType> selectPageDictTypeList(SysDictType dictType) {
        return PageUtils.buildDataInfo(baseMapper.selectPageDictTypeList(PageUtils.buildPage(), dictType));
    }

    /**
     * 根据字典类型查询字典数据
     *
     * @param dictType 字典类型
     * @return 字典数据集合信息
     */
    @Override
    public List<SysDictData> selectDictDataByType(String dictType) {
        List<SysDictData> dictDataList = redisUtils.get(getCacheKey(dictType), List.class);
        if (CollUtil.isNotEmpty(dictDataList)) {
            return dictDataList;
        }
        dictDataList = dictDataService.selectDictDataByType(dictType);
        if (CollUtil.isNotEmpty(dictDataList)) {
            redisUtils.set(getCacheKey(dictType), JSONObject.toJSONString(dictDataList));
            return dictDataList;
        }
        return null;
    }

    /**
     * 校验字典类型称是否唯一
     *
     * @param dict 字典类型
     * @return 结果
     */
    @Override
    public boolean checkDictTypeUnique(SysDictType dict) {
        Long dictId = ObjectUtil.isNull(dict.getDictId()) ? -1L : dict.getDictId();
        SysDictType dictType = getOne(new LambdaQueryWrapper<SysDictType>()
                .eq(SysDictType::getDictType, dict.getDictType())
                .last("limit 1"));

        if (ObjectUtil.isNotNull(dictType) && dictType.getDictId().longValue() != dictId.longValue()) {
            return false;
        }
        return true;
    }

    /**
     * 新增保存字典类型信息
     *
     * @param dict 字典类型信息
     * @return 结果
     */
    @Override
    public int insertDictType(SysDictType dict) {
        int row = baseMapper.insert(dict);
        if (row > 0) {
            redisUtils.set(getCacheKey(dict.getDictType()), "[]");
        }
        return row;
    }


    /**
     * 修改保存字典类型信息
     *
     * @param dict 字典类型信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateDictType(SysDictType dict) {
        SysDictType oldDict = getById(dict.getDictId());
        dictDataService.update(null, new LambdaUpdateWrapper<SysDictData>()
                .set(SysDictData::getDictType, dict.getDictType())
                .eq(SysDictData::getDictType, oldDict.getDictType()));
        int row = baseMapper.updateById(dict);
        if (row > 0) {
            List<SysDictData> dictDataList = dictDataService.selectDictDataByType(dict.getDictType());
            redisUtils.set(getCacheKey(dict.getDictType()), JSONObject.toJSONString(dictDataList));
        }
        return row;
    }


    /**
     * 批量删除字典类型信息
     *
     * @param dictIds 需要删除的字典ID
     * @return 结果
     */
    @Override
    public void deleteDictTypeByIds(Long[] dictIds) {
        for (Long dictId : dictIds) {
            SysDictType dictType = selectDictTypeById(dictId);
            if (dictDataService.count(new LambdaQueryWrapper<SysDictData>()
                    .eq(SysDictData::getDictType, dictType.getDictType())) > 0) {
                throw new ServiceException(String.format("%1$s已分配,不能删除", dictType.getDictName()));
            }
            redisUtils.delete(getCacheKey(dictType.getDictType()));
        }
        baseMapper.deleteBatchIds(Arrays.asList(dictIds));
    }


    /**
     * 重置字典缓存数据
     */
    @Override
    public void resetDictCache() {
        clearDictCache();
        loadingDictCache();
    }
}
